#include"./wifi.h"


network::network()
{
  this->stream.clear();
  
}
//函数功能：连接wifi
//函数参数：无
//函数返回值：void
void network::connectToWiFi()
{
  // 波特率
  //Serial.begin(9600);
  Serial.println("Starting setup...");
  WiFi.mode(WIFI_STA);
  WiFi.begin(this->ssid, this->password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  //启动服务器
  this->Server = WiFiServer(9596);
  this->Server.begin();
  Serial.println("Server started");
  //检查是否有客户端连接
  //this->Client = this->Server.available();
  
}
WiFiServer network::retserver()
{
  return this->Server;
}
//函数功能：阻塞接收客户端发送的信息
//函数参数：无
//函数返回值：String
String network::echoData()
{
   this->package.clear();
    //检查是否有客户端连接,阻塞
   if(!this->Client)
   {
     while(1)
     {
        Serial.print("wait....");
        delay(1000);
        this->Client = this->Server.available();
        if(this->Client)
        {
            break;
        }
     }
  }
  if(this->Client)
  {
    if(Client.connected())
    {
      while (!Client.available())
      {
        delay(100);  // 等待 100 毫秒，避免 CPU 占用过高
      }
      while(Client.available())
      {
        Serial.print("recv....\n");
        this->stream = this->Client.readStringUntil('\r\n');
        if (this->stream.length() == 0)
        {
          Serial.println("未接收到有效数据，继续等待...");
          delay(100);  
          continue;
        }
        this->package+=this->stream;
        //Serial.println(this->package); 
      }
      Serial.println("over...\n");
      return this->package;     
    }
    else
    {
      Serial.println("Client disconnected");
      this->Client.stop(); // 断开客户端连接，释放资源
    }
  }
  else
  {
    Serial.println("No client connected");
  }
  return "";
  
}
